package com.zjk.wrench.design.framework.tree.node;

import com.zjk.wrench.design.framework.tree.AbstractDemoSupport;
import com.zjk.wrench.design.framework.tree.StrategyHandler;
import com.zjk.wrench.design.framework.tree.factory.DefaultStrategyFactory;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Component
@Slf4j
@RequiredArgsConstructor
public class AccountNode extends AbstractDemoSupport {

    private final MemberLevel1Node memberLevel1Node;
    private final MemberLevel2Node memberLevel2Node;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;



    @Override
    protected void multiThread(String requestParameters, DefaultStrategyFactory.DynamicContext dynamicContext) {
        CompletableFuture<String> memberLevel01 = CompletableFuture.supplyAsync(() -> {
            log.info("异步查询账户标签，账户标签；开户|冻结|止付|可用");
            return new Random().nextBoolean() ? "可用" : "冻结";
        }, threadPoolExecutor);
        CompletableFuture<String> memberLevel02 = CompletableFuture.supplyAsync(() -> {
            log.info("异步查询授信数据，拦截|已授信|已降档");
            return new Random().nextBoolean() ? "拦截" : "已授信";
        }, threadPoolExecutor);

        CompletableFuture.allOf(memberLevel01, memberLevel02).thenAccept((v) -> {
            dynamicContext.setValue("memberLevel01", memberLevel01.join());
            dynamicContext.setValue("memberLevel02", memberLevel02.join());
        }).join();
    }

    @Override
    protected String doApply(String requestParameters, DefaultStrategyFactory.DynamicContext dynamicContext) throws Exception {
        log.info("【账户节点】规则决策树 requestParameters:{}", requestParameters);

        // 模拟查询用户级别
        int level = new Random().nextInt(2);
        log.info("模拟查询用户级别 level:{}", level);

        dynamicContext.setLevel(level);

        return router(requestParameters, dynamicContext);

    }

    @Override
    public StrategyHandler<String, DefaultStrategyFactory.DynamicContext, String> getStrategy(String requestParameters, DefaultStrategyFactory.DynamicContext dynamicContext) {
        String memberLevel01 = dynamicContext.getValue("memberLevel01");
        String memberLevel02 = dynamicContext.getValue("memberLevel02");
        int level = dynamicContext.getLevel();

        if ("账户冻结".equals(memberLevel01)) {
            return memberLevel1Node;
        }

        if ("拦截".equals(memberLevel02)) {
            return memberLevel1Node;
        }

        if (level == 1) {
            return memberLevel1Node;
        }

        return memberLevel2Node;


    }

}
